package com.lianyi.push.share.code;

import com.lianyi.push.entity.SmartCarProtocol;
import com.lianyi.push.share.ConstantValue;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;


public class SmartCarDecoder extends ByteToMessageDecoder {

    public final int BASE_LENGTH = 4 + 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer,
                          List<Object> out) throws Exception {
        if (buffer.readableBytes() >= BASE_LENGTH) {
            if (buffer.readableBytes() > ConstantValue.TCP_RECEIVE_SIZE) {
                buffer.skipBytes(buffer.readableBytes());
            }
            int beginReader;
            while (true) {
                beginReader = buffer.readerIndex();
                buffer.markReaderIndex();
                if (buffer.readInt() == ConstantValue.HEAD_DATA) {
                    break;
                }
                buffer.resetReaderIndex();
                buffer.readByte();
                if (buffer.readableBytes() < BASE_LENGTH) {
                    return;
                }
            }
            int length = buffer.readInt();
            if (buffer.readableBytes() < length) {
                buffer.readerIndex(beginReader);
                return;
            }
            byte[] data = new byte[length];
            buffer.readBytes(data);
            SmartCarProtocol protocol = new SmartCarProtocol(data.length, data);
            out.add(protocol);
        }
    }

}